#!/usr/bin/env python
# -*- coding: utf-8 -*-
import atexit
import os
import os.path
import sys
import xmmsclient
import xmmsqt4
from PyQt4 import QtCore, QtGui

CONFIG = "diskBrowser.conf"


def loadConfig(diskBrowser):
    try:
        config = open(CONFIG)
    except IOError:
        print "Could not read %s" % CONFIG
        return True
    for line in  config:
        path = line.strip()
        if path:
            diskBrowser.setCurrentDir(path)
            return True
    return False


def saveConfig(diskBrowser):
    lastDir = diskBrowser.currentDir()
    config = open(CONFIG, "w")
    print >>config, lastDir, "\n"
    config.close()


class DiskBrowser(QtGui.QWidget):
    def __init__(self, xmms2):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.xmms2 = xmms2
        self.completer = QtGui.QCompleter()
        self.gotoLine = QtGui.QLineEdit()
        self.gotoLine.setCompleter(self.completer)
        self.model = QtGui.QDirModel()
        self.model.setFilter(QtCore.QDir.AllEntries)
        self.model.setSorting(QtCore.QDir.DirsFirst)
        self.completer.setModel(self.model)
        self.view = QtGui.QListView()
        self.view.setModel(self.model)
        self.view.setRootIndex(self.model.index(QtCore.QDir.currentPath()))
        layout.addWidget(self.gotoLine)
        layout.addWidget(self.view)
        self.connect(self.gotoLine, QtCore.SIGNAL("returnPressed()"),
                     self.goto)
        self.connect(self.view, QtCore.SIGNAL("activated(QModelIndex)"),
                     self.selectFile)

    def currentDir(self):
        return unicode(self.model.filePath(self.view.rootIndex()))

    def goto(self):
        path = unicode(self.gotoLine.text())
        if os.path.exists(path) and os.path.isdir(path):
            self.view.setRootIndex(self.model.index(path))
        else:
            path = self.model.filePath(self.view.rootIndex())
            self.gotoLine.setText(path)
          
    def selectFile(self, index):
        if self.model.isDir(index):
            self.gotoLine.setText(self.model.filePath(index))
            self.view.setRootIndex(index)
        else:
            path = unicode(self.model.filePath(index))
            url = "file://" + path
            self.xmms2.playlist_add_url(url)
            
    def setCurrentDir(self, path):
        self.gotoLine.setText(path)
        self.view.setRootIndex(self.model.index(path))

    
if __name__ == "__main__":
    xmms2 = xmmsclient.XMMS("diskBrowser")
    try:
        xmms2.connect(os.getenv("XMMSPATH"))
    except IOError, detail:
        print "Could not connect to xmms2!", detail
        exit(1)
        
    app = QtGui.QApplication(sys.argv)
    xmmsqt4.XMMSConnector(xmms2, app)    
    diskBrowser = DiskBrowser(xmms2)
    atexit.register(saveConfig, diskBrowser)
    loadConfig(diskBrowser)
    diskBrowser.show()
    sys.exit(app.exec_())
